/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Principal;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Properties;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author EliteBook
 */
public class CambiarSucursal extends javax.swing.JDialog {

    /**
     * Creates new form CambiarSucursal
     */
    Vector sucursal = new Vector();
    PreparedStatement ps;
    VentanaPrincipal ventana;

    public CambiarSucursal(java.awt.Frame parent, boolean modal, VentanaPrincipal ventana) {
        super(parent, modal);
        initComponents();
        this.ventana = ventana;
        cargarDatos();

    }

    private void cargarDatos() {
        try {
            int sucu = 0;
            ps = local_connection.cn.prepareStatement("select id, nombre from sucursales where activo = 1");
            ResultSet rs = ps.executeQuery();
            for (int i = 0; rs.next(); i++) {
                sucursal.add(rs.getInt("id"));
                nSucursal.addItem(rs.getString("nombre"));
                if (rs.getInt("id") == VentanaPrincipal.sucursal) {
                    sucu = i;
                }
            }
            caja.setValue(VentanaPrincipal.caja);
            try {
                caja.commitEdit();
            } catch (ParseException ex) {
                VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
            }
            nSucursal.setSelectedIndex(sucu);
        } catch (SQLException ex) {
            VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        nSucursal = new javax.swing.JComboBox();
        caja = new javax.swing.JSpinner();
        pass = new javax.swing.JPasswordField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        jLabel1.setText("Elige tu sucursal:");

        jLabel2.setText("Elige tu caja:");

        jLabel3.setText("Contraseña:");

        caja.setModel(new javax.swing.SpinnerNumberModel(1, 1, 99, 1));

        jButton1.setText("Aceptar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Cancelar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(pass, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(nSucursal, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(caja, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(42, 42, 42)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton2)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(nSucursal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(caja, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(pass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
FileOutputStream os = null;
        try {
            
            caja.commitEdit();
            ps = local_connection.cn.prepareStatement("select id,nombre from sucursales where pass = ?");
            ps.setString(1, String.valueOf(pass.getPassword()));
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                if (rs.getInt(1) == (int) sucursal.elementAt(nSucursal.getSelectedIndex())) {
                    Properties propiedades;
                    jcProperties editarPropiedades;
                    editarPropiedades= new jcProperties();
                    propiedades = new Properties();
                    propiedades = editarPropiedades.getProperties();
                    propiedades.setProperty("caja", String.valueOf(caja.getValue()));
                    propiedades.setProperty("sucursal", String.valueOf(sucursal.elementAt(nSucursal.getSelectedIndex())));
                    VentanaPrincipal.sucursal = (int) sucursal.elementAt(nSucursal.getSelectedIndex());
                    VentanaPrincipal.caja = (int) caja.getValue();
                    ventana.setTitle("TeslaBEM Caja " + VentanaPrincipal.caja + " " + rs.getString(2));
                    ps = local_connection.cn.prepareStatement("update sesion set sucursal = ?, caja = ? where id = ?");
                    ps.setInt(1, VentanaPrincipal.sucursal);
                    ps.setInt(2, VentanaPrincipal.caja);
                    ps.setInt(3, VentanaPrincipal.sesionId);
                    ps.execute();
                    os=new FileOutputStream("Propiedades.properties");
                    propiedades.store(os, "Base de Datos Local");
                    this.dispose();
                } else {
                    JOptionPane.showMessageDialog(null, "Sucursal Incorrecta", "Error", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(null, "Contraseña Incorrecta", "Error", JOptionPane.ERROR_MESSAGE);
            }

            // TODO add your handling code here:
        } catch (ParseException | SQLException |FileNotFoundException ex) {
            VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CambiarSucursal.class.getName()).log(Level.SEVERE, null, ex);
        } 
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.dispose();
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JSpinner caja;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JComboBox nSucursal;
    private javax.swing.JPasswordField pass;
    // End of variables declaration//GEN-END:variables
}
